package com.mlh.springboot.controller;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestAttribute;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;

/**
 * @author 缪林辉
 * @date 2024/3/1 19:41
 * @DESCRIPTION
 */
@Controller
public class RequestController {
    @GetMapping("/login")
    public String login(HttpServletRequest request){
        request.setAttribute("user","mlh");
        return "forward:/ok"; //转发到 /ok
    }

    @ResponseBody
    @GetMapping("/ok")
    public String ok(@RequestAttribute(value = "user", required = false) String user,
                     HttpServletRequest request) {
        System.out.println("request 域中 user= " + user);
        System.out.println("request 域中 user= " + request.getAttribute("user"));
        return "success";
    }

    @GetMapping("/register")
    public String register(Map<String, Object> map,
                           Model model,
                           HttpServletResponse response) {
        map.put("user", "hspedu");
        map.put("job", "java 架构师");
        model.addAttribute("sal", 999999.9);
        //可以将 cookie 加入到 response 对象,返回给客户端
        Cookie cookie = new Cookie("pwd","666666");
        response.addCookie(cookie);
        return "forward:/registerOk";
    }

    @ResponseBody
    @GetMapping("/registerOk")
    public String registerOk(HttpServletRequest request) {
        System.out.println("request 域中 user= " + request.getAttribute("user"));
        System.out.println("request 域中 job= " + request.getAttribute("job"));
        System.out.println("request 域中 sal= " + request.getAttribute("sal"));
        return "success";
    }
}
